//
//  BookThemeCommentListViewController.m
//  QiYReader
//
//  Created by 奇阅科技 on 14/12/3.
//  Copyright (c) 2014年 奇阅科技. All rights reserved.
//

#import "BookThemeCommentListViewController.h"
#import "ZMYBookCommenHeadTableViewCell.h"
#import "ZMYBookCommenTableViewCell.h"
#import "TextInputView.h"
#import "UIScrollView+VORefresh.h"
#import "Config.h"
#import "ZMYThemeCommentTableViewController.h"
@interface BookThemeCommentListViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    TextInputView *inputView;
    __weak IBOutlet UIImageView *noCommentImageView;
    BOOL isHasMore;
}
@property (nonatomic,strong)NSMutableArray *commentDataArray;
@end

@implementation BookThemeCommentListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBarBackgroundImage:@"navBackground"];
    [self setLeftBackButtonForNavigation];
    [self setTitleForNavigation:@"书评"];
    // Do any additional setup after loading the view.
    [self.commentTableView addTopRefreshWithTarget:self action:@selector(getNetNewDataArray)];
    [self.commentTableView addBottomRefreshWithTarget:self action:@selector(getMoreDataArray)];
    _commentDataArray = [[NSMutableArray alloc]init];
    [self.commentDataArray addObject:[[ZMYLKDB getLKDBHelper] getThemeCommentWith:self.book.articleid]];
    [self.commentTableView reloadData];
    [self getNetNewDataArray];
    if ([self.book.articleid hasPrefix:@"qiyou"]) {
        self.textInputViewSuperView.hidden = YES;
    }
    __weak typeof(self) weakSelf = self;
    inputView = [[TextInputView alloc]initWithTitle:@"写书评" textString:^(NSString *textString) {
        ThemeComment *comment = [ThemeComment new];
        UserAccount *user = [UserAccount currentAccount];
        comment.uid = user.uid;
        comment.book = weakSelf.book;
        comment.articleid = weakSelf.book.articleid;
        comment.time = [NSString stringWithFormat:@"%.f",[ZMYNetWorkAPI currentTime]];
        comment.nickName = user.nickname.length>1?user.nickname:user.username;
        comment.headimg = user.headimg;
        comment.contents = textString;
        comment.point_like = @"0";
        comment.reply_num = @"0";
        if (weakSelf.commentDataArray.count==0) {
            weakSelf.commentDataArray = [NSMutableArray arrayWithObject:@[comment]];
            [weakSelf.commentTableView reloadData];
        } else if (weakSelf.commentDataArray.count==1) {
            NSMutableArray *newArray = [weakSelf.commentDataArray objectAtIndex:0];
            [newArray insertObject:comment atIndex:0];
            [weakSelf.commentTableView reloadData];
            [weakSelf.commentTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        } else {
            NSMutableArray *newArray = [weakSelf.commentDataArray objectAtIndex:1];
            [newArray insertObject:comment atIndex:0];
            [weakSelf.commentTableView reloadData];
            [weakSelf.commentTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
        [weakSelf.navigationController setSGProgressPercentage:1 andTintColor:YellowColor];
        [[ZMYNetWorkAPI default]commentWithArticleid:weakSelf.book content:textString response:^(NSDictionary *resultDic) {
            comment.commentid = [resultDic objectForKey:@"commentsid"];
            [[ZMYLKDB getLKDBHelper]updateThemeComment:comment];
            [weakSelf.navigationController setSGProgressPercentage:100 andTintColor:YellowColor];
        } progress:^(CGFloat progres) {
            [weakSelf.navigationController setSGProgressPercentage:progres*100 andTintColor:YellowColor];
        } error:^(NSString *errorStr) {
            [weakSelf.navigationController cancelSGProgress];
        }];
    }];

}
-(void)getNetNewDataArray{
    if ([self.book.articleid hasPrefix:@"qiyou"]) {
        [self.commentTableView.topRefresh endRefreshing];
        return;
    }
    [[ZMYNetWorkAPI default]getThemeComment:self.book commentsid:@"0" Response:^(NSDictionary *resultDic) {
        _commentDataArray = [[NSMutableArray alloc]initWithCapacity:0];
        NSMutableArray *hotArray = [resultDic objectForKey:@"hot_comments"];
        if (hotArray.count>0) {
            [self.commentDataArray addObject:hotArray];
        }
        NSMutableArray *commentArray = [resultDic objectForKey:@"commentsList"];
        if (commentArray.count>0) {
            [self.commentDataArray addObject:commentArray];
        }
        NSInteger count = [[resultDic objectForKey:@"count"] integerValue];
        if (commentArray.count<count) {
            isHasMore = YES;
        } else {
            isHasMore = NO;
            [self.commentTableView removeBottomRefresh];
        }
        [self.commentTableView reloadData];
        [self.commentTableView.topRefresh endRefreshing];
    } error:^(NSString *errorStr) {
        [self.commentTableView.topRefresh endRefreshing];
    }];
}
-(void)getMoreDataArray{
    if (isHasMore) {
        ThemeComment *comment = [[self.commentDataArray lastObject] lastObject];
        [[ZMYNetWorkAPI default]getThemeComment:self.book  commentsid:comment.commentid Response:^(NSDictionary *resultDic) {
            [self.commentTableView.bottomRefresh endRefreshing];
            NSMutableArray *commentList = [resultDic objectForKey:@"commentsList"];
            NSMutableArray *commentArray = [self.commentDataArray lastObject];
            if (commentArray) {
                [commentArray addObjectsFromArray:commentList];
            } else {
                [self.commentDataArray addObject:commentList];
            }
            commentArray = [self.commentDataArray lastObject];
            NSInteger count = [[resultDic objectForKey:@"count"] integerValue];
            if (commentArray.count<count) {
                isHasMore = YES;
            } else {
                isHasMore = NO;
                [self.commentTableView removeBottomRefresh];
            }
            [self.commentTableView reloadData];
            
        } error:^(NSString *errorStr) {
            [self.commentTableView.bottomRefresh endRefreshing];
            [AppDelegate showHUDAndHide:errorStr view:self.view];
        }];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    if (!self.commentDataArray||self.commentDataArray.count == 0) {
        noCommentImageView.frame = CGRectMake((SCREEN_WIDTH/2)-103, (tableView.frame.size.height/2)-45, 207, 90);
        noCommentImageView.hidden = NO;
        return 0;
    }
    NSArray *array = [self.commentDataArray objectAtIndex:0];
    if (array.count<1) {
        noCommentImageView.frame = CGRectMake((SCREEN_WIDTH/2)-103, (tableView.frame.size.height/2)-45, 207, 90);
        noCommentImageView.hidden = NO;
    } else {
        noCommentImageView.hidden = YES;
    }
    return self.commentDataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return ((NSArray *)[self.commentDataArray objectAtIndex:section]).count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ThemeComment *comment = [[self.commentDataArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    CGSize commSize = [comment.contents boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-16, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil].size;
    if (indexPath.row == 0) {
        return commSize.height+107;
    } else {
        return commSize.height+72;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ThemeComment *comment = [[self.commentDataArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    if (indexPath.row == 0) {
        ZMYBookCommenHeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZMYBookCommenHeadTableViewCell" forIndexPath:indexPath];
        if (indexPath.section == 0 &&self.commentDataArray.count>1) {
            cell.titleImageView.image = [UIImage imageNamed:@"hotComment"];
        } else {
            cell.titleImageView.image = [UIImage imageNamed:@"newComment"];
        }
        [cell.headImageView setImageWithURL:[NSURL URLWithString:comment.headimg]placeholderImage:[UIImage imageNamed:@"touxiang"]];
        cell.nickNameLabel.text = comment.nickName;
        cell.timeLabel.text = [NSString intDateToStrFromNSTimeInterval:comment.time];
        cell.commentLabel.text = comment.contents;
        cell.praiseNumLabel.text = comment.point_like;
        cell.commentNumLabel.text = comment.reply_num;
        LikeComment *like = [LikeComment new];
        like.articleid = comment.articleid;
        like.commentid = comment.commentid;
        UserAccount *user = [UserAccount currentAccount];
        if (!user) {
            like.uid = @"love";
        } else {
            like.uid = user.uid;
        }
        if ([[ZMYLKDB getLKDBHelper]getIsLike:like]) {
            cell.likeImageView.image = [UIImage imageNamed:@"mypraise"];
            cell.praiseNumLabel.textColor = [UIColor whiteColor];
        } else {
            cell.likeImageView.image = [UIImage imageNamed:@"mynopraise"];
            cell.praiseNumLabel.textColor = RGB_COLOR(160, 160, 160);
        }
        cell.comment = comment;
        return cell;
    }
    ZMYBookCommenTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZMYBookCommenTableViewCell" forIndexPath:indexPath];
    [cell.headImageView setImageWithURL:[NSURL URLWithString:comment.headimg]placeholderImage:[UIImage imageNamed:@"touxiang"]];
    cell.nickNameLabel.text = comment.nickName;
    cell.timeLabel.text = [NSString intDateToStrFromNSTimeInterval:comment.time];
    cell.commentLabel.text = comment.contents;
    cell.praiseNumLabel.text = comment.point_like;
    cell.commentNumLabel.text = comment.reply_num;
    LikeComment *like = [LikeComment new];
    like.articleid = comment.articleid;
    like.commentid = comment.commentid;
    UserAccount *user = [UserAccount currentAccount];
    if (!user) {
        like.uid = @"love";
    } else {
        like.uid = user.uid;
    }
    if ([[ZMYLKDB getLKDBHelper]getIsLike:like]) {
        cell.likeImageView.image = [UIImage imageNamed:@"mypraise"];
        cell.praiseNumLabel.textColor = [UIColor whiteColor];
    } else {
        cell.likeImageView.image = [UIImage imageNamed:@"mynopraise"];
        cell.praiseNumLabel.textColor = RGB_COLOR(160, 160, 160);
    }
    cell.comment = comment;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ThemeComment *comment = [[self.commentDataArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    ZMYThemeCommentTableViewController *view = [self.storyboard instantiateViewControllerWithIdentifier:@"ZMYThemeCommentTableViewController"];
    view.themeComment = comment;
    [self.navigationController pushViewController:view animated:YES];
}
#pragma mark - 输入框的显示隐藏和发表评论

- (IBAction)inputCommentClick:(id)sender {
    //显示输入框
    [inputView showInputView];
}
@end
